﻿using System;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.Globalization;
using Microsoft.Practices.ObjectBuilder;
using WCSFContrib.ECommerceCatalog.BusinessEntities;

namespace WCSFContrib.ECommerceCatalog.User.Views
{
    public partial class Cart : Microsoft.Practices.CompositeWeb.Web.UI.Page, ICartView
    {
        private CartPresenter _presenter;
        const string DeleteProductCommand = "DeleteCartProduct";
        const string ShowProductDetailsCommand = "ShowProductDetails";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                this._presenter.OnViewInitialized();
            }
            this._presenter.OnViewLoaded();
        }

        [CreateNew]
        public CartPresenter Presenter
        {
            set
            {
                this._presenter = value;
                this._presenter.View = this;

                this._presenter.UserName = User.Identity.Name;
            }
        }

        protected void ProductsCartGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int itemId = int.Parse((string)e.CommandArgument, CultureInfo.CurrentCulture);
            
            if (e.CommandName == DeleteProductCommand)
            {
                string userName = User.Identity.Name;
                //int rowIndex = int.Parse((string)e.CommandArgument, CultureInfo.CurrentCulture);
                int quantity = 999; //int.Parse((((GridView)e.CommandSource).Rows[rowIndex].Cells[5].Text), CultureInfo.CurrentCulture);

                _presenter.OnDeleteProduct(userName, itemId, quantity);
            }
            else if (e.CommandName == ShowProductDetailsCommand)
            {
                _presenter.OnProductDetailsRequested(itemId);
            }
        }

        protected void CheckoutButton_Click(object sender, EventArgs e)
        {
            if (ProductsCartGridView.Rows.Count > 0)
                _presenter.OnCheckoutOrder();
        }

        #region ICartView Members

        public void ShowCart(BusinessEntities.Cart cart)
        {
            if (cart == null)
            {
                string emptyTotal = "0";
                TotalLabel.Text = String.Format(CultureInfo.CurrentCulture, "$ {0}", emptyTotal);
                ProductsCartGridView.DataSource = null;
            }
            else
            {
                TotalLabel.Text = String.Format(CultureInfo.CurrentCulture, "$ {0}", cart.Total);
                ProductsCartGridView.DataSource = cart.CartItems;
            }

            ProductsCartGridView.DataBind();
        }

        public void ShowProductDetails(Item item)
        {
            ProductDetailsUserControl.ShowProductDetails(item);
            DetailsModalPopupExtender.Show();
        }

        #endregion
    }
}

